﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;

namespace uComponents.RazorModels
{
	internal class Helper
	{
		internal static bool CouldItBeXml(string xml)
		{
			if (!string.IsNullOrEmpty(xml))
			{
				xml = xml.Trim();

				if (xml.StartsWith("<") && xml.EndsWith(">"))
				{
					return true;
				}
			}

			return false;
		}

		internal static List<int> GetCsvIds(string csv)
		{
			var ids = new List<int>();
			int id;

			if (!string.IsNullOrEmpty(csv))
			{
				var items = csv.Split(',').Select(s => s.Trim());
				foreach (var item in items)
				{
					if (int.TryParse(item, out id))
					{
						ids.Add(id);
					}
				}
			}

			return ids;
		}

		internal static List<int> GetXmlIds(string xml)
		{
			var ids = new List<int>();
			int id;

			if (!string.IsNullOrEmpty(xml))
			{
				using (XmlReader xmlReader = XmlReader.Create(new StringReader(xml)))
				{
					try
					{
						xmlReader.Read();

						// Check name of first element
						switch (xmlReader.Name)
						{
							case "MultiNodePicker":
							case "XPathCheckBoxList":
							case "CheckBoxTree":

								// Position on first <nodeId>
								xmlReader.ReadStartElement();

								while (!xmlReader.EOF)
								{
									if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "nodeId")
									{
										if (int.TryParse(xmlReader.ReadElementContentAsString(), out id))
										{
											ids.Add(id);
										}
									}
									else
									{
										// Step the reader on
										xmlReader.Read();
									}
								}
								break;
						}

					}
					catch
					{
						// Failed to read as Xml
					}
				}
			}

			return ids;
		}
	}
}
